<template>
  <div class="power-statistics">
    <div class="header">
      <h1>{{ title }}</h1>
      <!-- <button class="toggle-scroll" @click="toggleAutoScroll">
        {{ isAutoScrolling ? '停止滚动' : '开始滚动' }}
      </button> -->
    </div>
    <div ref="chartContainer" class="chart"></div>
  </div>
</template>

<script>
import axios from 'axios'
import * as echarts from 'echarts'

export default {
  name: 'PowerStatistics',
  props: {
    title: {
      type: String,
      default: '24小时电力统计'
    },
    apiUrl: {
      type: String,
      default: 'http://192.168.5.22:3000/api/users/6/AH1_IPA/20250101/2'
    },
    autoScrollSpeed: {
      type: Number,
      default: 3000 // 滚动速度，毫秒
    },
    scrollStep: {
      type: Number,
      default: 1 // 每次滚动的步长（百分比）
    },
    windowSize: {
      type: Number,
      default: 30 // 视窗大小（百分比）
    }
  },
  data() {
    return {
      chart: null,
      powerData: [],
      dataTimer: null,
      scrollTimer: null,
      isAutoScrolling: true,
      currentStart: 0,
      currentEnd: 30, // 默认视窗大小
      resizeHandler: null
    }
  },
  mounted() {
    this.initChart()
    this.fetchPowerData()
    
    // 数据更新定时器 - 每5分钟获取一次新数据
    this.dataTimer = setInterval(() => {
      // this.fetchPowerData()
    }, 5 * 60 * 1000)
    
    // Set up resize handler
    this.resizeHandler = () => {
      this.adjustChartSize(); // Call adjustChartSize on resize
    };
    window.addEventListener('resize', this.resizeHandler);

    // 启动自动滚动
    this.startAutoScroll()
    // 保证组件卸载时清理资源
    this.$once('hook:beforeDestroy', this.cleanup)
  },
  methods: {
    isMobile() {
      // Basic check using userAgent or window width
      if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        return true;
      }
      // You can also check window width as a fallback or primary method
      // return window.innerWidth <= 768; 
      return false; // Default to desktop
    },

    adjustChartSize() {
      if (!this.$refs.chartContainer) return;
      const container = this.$refs.chartContainer;
      if (this.isMobile()) {
        // Set width for mobile (e.g., 100% of viewport width minus padding)
        container.style.width = 'calc(100vw - 40px)'; // Adjust 40px based on parent padding
        container.style.height = '300px'; // Adjust height for mobile if needed
      } else {
        // Set width for desktop (e.g., 100% of container)
        container.style.width = '100%'; 
        container.style.height = '500px'; // Original desktop height
      }
      // Resize the ECharts instance
      if (this.chart) {
        this.chart.resize();
      }
    },

    initChart() {
      if (this.$refs.chartContainer) {
        this.chart = echarts.init(this.$refs.chartContainer)
        
        // 初始化空图表
        this.updateChart([])
        
        // 设置窗口大小变化时的响应
        this.resizeHandler = () => {
          if (this.chart) {
            this.chart.resize()
          }
        }
        window.addEventListener('resize', this.resizeHandler)
        
        // Initial size adjustment
        this.adjustChartSize();
        
        // 监听图表交互事件
        this.chart.on('datazoom', (params) => {
          // 用户手动缩放时停止自动滚动
          if (params.batch) {
            this.currentStart = params.batch[0].start
            this.currentEnd = params.batch[0].end
            this.stopAutoScroll()
          }
        })
      }
    },
    
    fetchPowerData() {
      // 尝试从API获取数据
      axios.get(this.apiUrl)
        .then(response => {
          this.powerData = response.data
          console.log(this.powerData)
          this.updateChart(this.powerData)
        })
        .catch(error => {
          console.error('Error fetching power data:', error)
          // API调用失败，使用模拟数据
          this.generateMockData()
        })
    },
    
    generateMockData() {
      // 生成24小时的模拟数据，每5分钟一个数据点
      const mockData = []
      const now = new Date()
      const startTime = new Date(now)
      startTime.setHours(0, 0, 0, 0)
      
      // 生成一天的数据（288个点 = 24小时 * 12个点/小时）
      for (let i = 0; i < 24 * 12; i++) {
        const time = new Date(startTime.getTime() + i * 5 * 60 * 1000)
        const hours = time.getHours().toString().padStart(2, '0')
        const minutes = time.getMinutes().toString().padStart(2, '0')
        const timeStr = `${hours}:${minutes}`
        
        // 生成随机数据，模拟一天的电力变化
        let value = 100
        
        // 早高峰 (7:00-9:00)
        if (hours >= 7 && hours < 9) {
          value = 140 + Math.random() * 30
        } 
        // 晚高峰 (18:00-21:00)
        else if (hours >= 18 && hours < 21) {
          value = 150 + Math.random() * 40
        } 
        // 夜间 (23:00-6:00)
        else if (hours >= 23 || hours < 6) {
          value = 60 + Math.random() * 20
        } 
        // 其它时间
        else {
          value = 100 + Math.random() * 30
        }
        
        // 添加小幅波动
        value += Math.sin(i / 12) * 10
        
        mockData.push({
          time: timeStr,
          value: Math.round(value)
        })
      }
      
      this.powerData = mockData
      this.updateChart(this.powerData)
    },
    
    updateChart(data) {
      if (!this.chart) return
      
      // 提取数据
      // const times = data.map(item => item.time || '')
      // const values = data.map(item => item.value || 0)
      const times = data.map(item => item.dateNum || '')
      const values = data.map(item => item.data || 0)
      // 构建图表配置
      const option = {
        title: {
          text: this.title,
          left: '10%',
          top: 10
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br />{a}: {c} kW/h',
          axisPointer: {
            type: 'line',
            lineStyle: {
              color: '#7581BD',
              width: 1,
              type: 'solid'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: times,
          boundaryGap: false,
          axisLabel: {
            interval: 0,
            rotate: 45,
            showMaxLabel: true,
            showMinLabel: true
          }
        },
        yAxis: {
          type: 'value',
          name: '电力 (kW/h)',
          nameLocation: 'end'
        },
        series: [{
          name: 'A项电流',
          type: 'line',
          smooth: true,
          symbol: 'none', // 不显示节点标记
          sampling: 'average', // 大数据采样
          data: values,
          itemStyle: {
            color: '#3a4de9'
          },
          markLine: {
            // symbol: 'none',
            data: [
            { 
                yAxis: 90, 
                name: '阈值A', 
                lineStyle: { color: '#629fd7', type: 'solid' },
                label:{
                  show: true,   // 显示标签
                  position: 'end', // 标签位置：'start'、'middle'、'end'
                  formatter: 'A项电流: {c}' // {c} 自动替换为 yAxis 值
                }
              },
              { 
                yAxis: 110.45, 
                name: '阈值B', 
                lineStyle: { color: '#00b050', type: 'solid' },
                label:{
                  show: true,   // 显示标签
                  position: 'end', // 标签位置：'start'、'middle'、'end'
                  formatter: '安全电流: {c}' // {c} 自动替换为 yAxis 值
                }
              },
              { 
                type: 'max', 
                name: '最大值', 
                lineStyle: { color: '#ed7d31',type: 'solid' },
                label:{
                  show: true,   // 显示标签
                  position: 'end', // 标签位置：'start'、'middle'、'end'
                  formatter: '极限电流: {c}' // {c} 自动替换为 yAxis 值
                }
              },
              {
                type: 'average',
                name: '平均电流',
                lineStyle: {color:'#a6a6a6', type: 'solid'},
                label:{
                  show: true,
                  position: 'end',
                  formatter: 'A项平均电流: {c}'
                }
              }
            ]
          }
        }],
        dataZoom: [
          {
            type: 'slider',
            show: false, // 隐藏滑动条
            startValue: this.currentStart,
            endValue: this.currentEnd,
            bottom: 10,
            zoomLock: false,
            realtime: true,
            filterMode: 'filter' // 数据过滤模式
          }, 
          {
            type: 'inside',
            startValue: this.currentStart,
            endValue: this.currentEnd,
            zoomLock: false,
            filterMode: 'filter'
          }
        ],
        grid: {
          bottom: 70,
        }
      }
      
      // 使用动画过渡更新图表
      this.chart.setOption(option, true)
    },
    
    startAutoScroll() {
      if (this.scrollTimer) {
        clearInterval(this.scrollTimer)
      }
      
      this.isAutoScrolling = true
      this.scrollTimer = setInterval(() => {
        if (!this.chart || !this.isAutoScrolling || this.powerData.length === 0) return
        
        const dataLength = this.powerData.length
        
        // 增加当前位置
        this.currentStart = (this.currentStart + this.scrollStep) % (dataLength - this.windowSize)
        this.currentEnd = this.currentStart + this.windowSize
        
        // 确保数值范围正确
        if (this.currentEnd >= dataLength) {
          this.currentEnd = dataLength - 1
        }
        
        // 如果已经滚动到尽头，重新开始
        if (this.currentStart >= dataLength - this.windowSize) {
          this.currentStart = 0
          this.currentEnd = this.windowSize
        }
        
        try {
          // 更新dataZoom位置
          this.chart.setOption({
            dataZoom: [
              {
                startValue: this.currentStart,
                endValue: this.currentEnd
              },
              {
                startValue: this.currentStart,
                endValue: this.currentEnd
              }
            ]
          }, false) // 不合并，保证顺畅滚动
        } catch (error) {
          console.error('Error updating chart:', error)
          // 出错时尝试恢复
          this.stopAutoScroll()
          setTimeout(() => this.startAutoScroll(), 1000)
        }
      }, this.autoScrollSpeed)
    },
    
    stopAutoScroll() {
      this.isAutoScrolling = false
      if (this.scrollTimer) {
        clearInterval(this.scrollTimer)
        this.scrollTimer = null
      }
    },
    
    toggleAutoScroll() {
      if (this.isAutoScrolling) {
        this.stopAutoScroll()
      } else {
        this.startAutoScroll()
      }
    },
    
    cleanup() {
      // 清理所有定时器和事件
      if (this.dataTimer) {
        clearInterval(this.dataTimer)
      }
      if (this.scrollTimer) {
        clearInterval(this.scrollTimer)
      }
      if (this.chart) {
        this.chart.dispose()
      }
      if (this.resizeHandler) {
        window.removeEventListener('resize', this.resizeHandler)
      }
    }
  },
  beforeDestroy() {
    this.cleanup(); // Use the cleanup method
  }
}
</script>

<style scoped>
.power-statistics {
  padding: 20px;
  font-family: Arial, sans-serif;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.toggle-scroll {
  /* padding: 8px 16px; */
  padding: 0.5rem 1rem; /* Use rem for padding */
  background-color: #3a4de9;
  color: white;
  border: none;
  border-radius: 4px; /* Can keep px for small radii or use rem */
  cursor: pointer;
  /* font-size: 14px; */
  font-size: 0.875rem; /* Use rem for font size */
  min-width: 80px; /* Ensure a minimum width */
  text-align: center; /* Center text if min-width makes button wider */
  transition: background-color 0.2s;
}
.toggle-scroll:hover {
  background-color: #2a3bd9;
}
.chart {
  /* Remove fixed width/height, let JS control it */
  /* width: 100%; */ 
  /* height: 500px; */
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  /* Ensure container itself doesn't cause overflow on small screens */
  overflow: hidden; 
}
</style> 